package cn.yunbamboos.mybatis.mapping.methods;

import cn.yunbamboos.mybatis.conditions.Conditions;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseQueryMethod extends BaseMethod {
    private static final Logger log = LoggerFactory.getLogger(BaseMethod.class);

    public BaseQueryMethod(String methodName, Configuration configuration, TableInfo tableInfo) {
        super(methodName, configuration, tableInfo, SqlCommandType.SELECT);
    }

    @Override
    protected MappedStatement.Builder getMappedStatementBuilder() {
        MappedStatement.Builder builder = super.getMappedStatementBuilder();
        List<ResultMap> resultMaps = getStatementResultMaps(tableInfo.getResultMap());
        builder.resultMaps(resultMaps);
        return builder;
    }

    @Override
    protected SqlSource getSqlSource() {
        return createSqlSource();
    }

    protected SqlSource createSqlSource() {
        return new RawSqlSource(configuration, getSQL(), Conditions.class);
    }

    protected String getSQL() {
        List<String> columns = new ArrayList<>();
        this.tableInfo.getPrimaryKeyList().forEach(pk -> {
            columns.add(BACKTICK + pk.getColumn() + BACKTICK);
        });
        this.tableInfo.getFieldList().forEach(field -> {
            columns.add(BACKTICK + field.getColumn() + BACKTICK);
        });
        return this.SELECT_ALL(columns, BACKTICK + this.tableInfo.getTableName() + BACKTICK);
    }


}
